import * as THREE from 'three';
import { BaseScene } from './BaseScene.js';

/**
 * 地面场景 - 只包含一个默认地面
 * 这是新项目的默认场景
 */
export class GroundScene extends BaseScene {
    constructor() {
        super('GroundScene');
        this.ground = null;
    }

    init(renderer) {
        // 设置背景 - 改为渐变天空色
        this.scene.background = new THREE.Color(0xa8d8ea); // 浅蓝天空色

        // 创建相机
        const aspect = window.innerWidth / window.innerHeight;
        // 🔧 修复 Z-fighting：优化 near 和 far 平面
        // near 适当增大，far 适当减小，可以提高深度精度
        // near: 0.01 -> 0.1（10倍），far: 5000 -> 10000（范围足够）
        this.camera = new THREE.PerspectiveCamera(75, aspect, 0.1, 10000);
        this.camera.position.set(50, 50, 50);
        this.camera.lookAt(0, 0, 0);

        // 设置统一的相机控制器（平移、旋转、缩放）
        this.setupCameraController(renderer, {
            target: { x: 0, y: 0, z: 0 },
            minDistance: 0,
            maxDistance: 2000
        });

        // 添加环境光
        const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
        this.scene.add(ambientLight);
        this.lights.push(ambientLight);

        // 添加平行光
        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
        directionalLight.position.set(5, 10, 7.5);
        directionalLight.castShadow = true;
        
        // 配置阴影
        directionalLight.shadow.mapSize.width = 2048;
        directionalLight.shadow.mapSize.height = 2048;
        directionalLight.shadow.camera.left = -500;
        directionalLight.shadow.camera.right = 500;
        directionalLight.shadow.camera.top = 500;
        directionalLight.shadow.camera.bottom = -500;
        
        this.scene.add(directionalLight);
        this.lights.push(directionalLight);

        // 创建地面
        this.createGround();

        // 设置比例尺（1000米×1000米网格）
        this.setupScaleGrid(1000);
    }

    createGround() {
        // 地面几何体 (1000x1000米)
        const groundGeometry = new THREE.PlaneGeometry(1000, 1000);
        
        // 地面材质
        const groundMaterial = new THREE.MeshStandardMaterial({
            color: 0x808080,
            roughness: 0.8,
            metalness: 0.2
        });

        this.ground = new THREE.Mesh(groundGeometry, groundMaterial);
        this.ground.rotation.x = -Math.PI / 2; // 旋转到水平
        this.ground.receiveShadow = true;
        this.ground.position.y = 0;
        this.ground.userData.isGround = true; // 标记为地面，方便环境控制

        this.scene.add(this.ground);
        this.objects.push(this.ground);

        // 添加网格辅助线 (1000米，100个格子，每格10米)
        const gridHelper = new THREE.GridHelper(1000, 100, 0x444444, 0x888888);
        gridHelper.userData.isGround = true; // 同样标记为地面的一部分
        this.scene.add(gridHelper);
        this.objects.push(gridHelper);
    }

    update(deltaTime) {
        // 调用基类的 update，确保相机控制器正常工作
        super.update(deltaTime);
        
        // 地面场景是静态的，不需要额外的更新
        // 可以在这里添加需要的动画效果
    }
}

